package com.hmall.item.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.ItemDoc;
import com.hmall.item.service.ItemService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ItemListener {
    @Autowired
    private ItemService itemService;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 监听删除操作,如果执行就删除es中该数据
     *
     * @param id
     */
    @RabbitListener(queues = "hmall.delete.queue")
    public void listenerToDelete(Long id) {
        DeleteRequest request = new DeleteRequest("item", String.valueOf(id));
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听新增操作
     */
    @RabbitListener(queues = "hmall.insert.queue")
    public void listenerToInsert(Item item) {
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest request = new IndexRequest("item");
        request.id(String.valueOf(itemDoc.getId()));
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);

        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
